using System;
using System.Web;
using System.Xml;
using Framework.Library.Core.Utils.Web.Handlers;

namespace Newtonsoft.Utilities.Web
{
    public abstract class XmlResponseHandlerBase : HandlerBase, IHttpHandler
    {
        #region IHttpHandler Members

        void IHttpHandler.ProcessRequest(HttpContext context)
        {
            if (context == null)
                throw new ArgumentNullException("context");

            Context = context;

            try
            {
                XmlResponse(context.Response, WriteResult);
            }
            catch (Exception exception)
            {
                context.AddError(exception);
                OnError(EventArgs.Empty);
                if (context.Error != null)
                {
                    throw new HttpUnhandledException("blah", exception);
                }
            }
        }

        bool IHttpHandler.IsReusable
        {
            get { return false; }
        }

        #endregion

        public event EventHandler Error;

        protected abstract void WriteResult(XmlTextWriter result);

        public static void XmlResponse(HttpResponse response, Action<XmlTextWriter> writeAction)
        {
            response.ClearHeaders();
            response.ClearContent();
            response.ContentType = "text/xml";

            var writer = new XmlTextWriter(response.Output);

            writeAction(writer);

            writer.Flush();
        }

        protected virtual void OnError(EventArgs e)
        {
            if (Error != null)
            {
                Error(this, e);
            }
        }
    }
}